import json
import re
import requests
from bs4 import BeautifulSoup

def get_location(url,encoding):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        response.encoding = encoding

        return response.text

    except requests.RequestException as e:
        print(f"请求错误: {e}")
        return None

def checkMobilePhone():
    phone_num = input("请输入要查询的号码: ")
    url = f"https://www.ip138.com/mobile.asp?mobile={phone_num}&action=mobile"
    location_info = get_location(url,'utf-8')

    if location_info:
        print("查询结果:")
        html = BeautifulSoup(location_info,'html.parser')

        info = html.find('div', {"class":"table"}).find_all('td')

        for i in range(0, len(info), 2):
            if i + 1 < len(info):
                title = info[i].text.strip().replace('\n', '').replace('\r', '')
                content_element = info[i + 1]

                # 提取纯文本内容，去除链接等HTML元素
                content = content_element.get_text(strip=True)

                # 特殊处理查询的号码标题
                if "您查询的" in title and "号码段" in title:
                    print(f" 查询号码 : {content}")
                    print("-" * 50)
                else:
                    # 根据标题类型格式化显示
                    if "归属地" in title:
                        print(f" {title} : {content}")
                    elif "运营商" in title:
                        print(f" {title} : {content}")
                    elif "区号" in title:
                        print(f" {title} : {content}")
                    elif "邮编" in title:
                        print(f" {title} : {content}")
                    elif "类型" in title:
                        if content:
                            print(f" {title} : {content}")
                        else:
                            print(f" {title} : 未知")
                    else:
                        print(f"  {title} : {content}")

def checkIP():
    ip_address = input("请输入要查询的IP地址: ")
    url = f"https://www.ip138.com/iplookup.asp?ip={ip_address}&action=2"
    location_info = get_location(url, 'gbk')

    if location_info:
        print("查询结果:")
        html = BeautifulSoup(location_info,'html.parser')
        scripts = html.find_all('script')
        for script in scripts:
            if script.string and 'ip_result' in script.string:
                # 提取ip_result变量
                match = re.search(r'var\s+ip_result\s*=\s*({.*?});', script.string, re.DOTALL)
                if match:
                    try:
                        ip_result = json.loads(match.group(1))
                        print("ASN归属地：{}".format(ip_result["ASN归属地"]))
                    except json.JSONDecodeError:
                        pass
        return None
    else:
        print("未能获取到信息，请检查输入的IP地址是否正确或网络连接。")
        return None

def start():
    while True:
        print("-" * 30)
        print("1.查号码")
        print("2.查ip")
        num = int(input("->"))
        if num == 1:
            checkMobilePhone()
        elif num == 2:
            checkIP()
        else:
            print("请输入指定数字")


if __name__ == "__main__":
    start()
